package com.ay.smartpark.sdk.common.rpc.mybatisConfig;

import com.alibaba.druid.pool.DruidDataSource;

import com.ay.smartpark.sdk.common.utils.YmlUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

@Configuration
public class RpcMybatisConfig {

    private static final Logger logger = LoggerFactory.getLogger(RpcMybatisConfig.class);

    @Bean(name = "rpcSqlSessionFactory")
    public SqlSessionFactory rpcSqlSessionFactory() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setDataSource(new DruidDataSource());
            bean.setPlugins(new Interceptor[]{new RpcInterceptor()});
            //每张表对应的xml文件
            bean.setMapperLocations(resolver.getResources(YmlUtils.getRpcMapperLocation("")));
            return bean.getObject();
        } catch (Exception e) {
            logger.error("init rpcSqlSessionFactory error:", e);
            throw new RuntimeException(e);
        }
    }

    @DependsOn("rpcSqlSessionFactory")
    @Bean
    public MapperScannerConfigurer rpcMapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("rpcSqlSessionFactory");
        //每张表对应的*.java,interface类型的Java文件
        mapperScannerConfigurer.setBasePackage(YmlUtils.getRpcBasePackage(""));
        return mapperScannerConfigurer;
    }
}
